package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.bean.*;
import com.itheima.common.BaseContext;
import com.itheima.dao.*;
import com.itheima.dto.OrdersDto;
import com.itheima.exception.CustomException;
import com.itheima.service.OrdersService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {

    @Autowired
    private OrdersDao ordersDao;

    @Autowired
    private OrderDetailDao orderDetailDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private AddressBookDao addressBookDao;

    @Autowired
    private ShoppingCartDao shoppingCartDao;

    @Override
    @Transactional
    public void sumbit(Orders orders) {
        //原因：要根据订单明细表中的商品单价和数量计算订单总金额
        //1.获取当前登录的用户id，查询用户信息 判断用户是否存在
        Long userId = BaseContext.getCurrentId();
        User user = userDao.selectById(userId);
        if(user==null){
            throw new CustomException(0,"请先登录，再下单！");
        }

        //2.根据地址id判断下单地址是否存在  	如果不存在，则无法下单
        AddressBook addressBook = addressBookDao.selectById(orders.getAddressBookId());
        if(addressBook==null){
            throw new CustomException(0,"请填写地址后再下单！");
        }

        //3.根据用户id获取当前用户购物车列表数据 判断用户购物车是否有商品 没有，则无法下单
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> carts = shoppingCartDao.selectList(wrapper);
        if(carts==null || carts.size()==0){
            throw new CustomException(0,"请选择商品后再下单！");
        }

        //提前手动生成订单id
        long orderId = IdWorker.getId();
        //BigDecimal：这种类型精度不会丢失  使用原子类型：保证并发环境下，线程安全
        //BigDecimal sumAccount = new BigDecimal(0);
        AtomicInteger sumAccount = new AtomicInteger(0);


        //4.保存订单下的商品信息到订单明细表 order_detail中 将当前用户 购物车中商品转存到 订单详情表中，并同时设置关联的订单id
        carts.stream().forEach(cart->{
            //计算总金额
            sumAccount.addAndGet((cart.getAmount().multiply(new BigDecimal(cart.getNumber()))).intValue()) ;

            //a:创建订单详情下的商品对象 OrderDetail
            OrderDetail orderDetail = new OrderDetail();

            //b：将cart对象中属性数据复制到 orderDetail对象中
            BeanUtils.copyProperties(cart,orderDetail);

            //c：设置订单项商品关联的订单id
            orderDetail.setOrderId(orderId);

            //d：将每一个订单项商品存入到order_detail中
            orderDetailDao.insert(orderDetail);
        });

        //5.保存订单基本信息到订单表 orders中
        //补全orders字段
        //1.订单id
        orders.setId(orderId);

        //2.订单号 订单号使用UUID随机生成一个唯一的字符串
        orders.setNumber(UUID.randomUUID().toString());

        //3.订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setStatus(2);

        //4.下单用户id
        orders.setUserId(userId);

        //5.地址id        前端传递
        //6.下单时间       使用当前时间
        orders.setOrderTime(LocalDateTime.now());

        //7.结账时间
        orders.setCheckoutTime(LocalDateTime.now());

        //8.支付方式 1微信，2支付宝  前端传递

        //9.实收金额
        orders.setAmount(new BigDecimal(sumAccount.intValue()));

        //10备注 前端传递

        //11.用户名
        orders.setUserName(user.getName());

        //12.手机号
        orders.setPhone(addressBook.getPhone());

        //13.地址
        orders.setAddress((addressBook.getProvinceName()==null?"":addressBook.getProvinceName())
                        +(addressBook.getCityName()==null?"":addressBook.getCityName())
                        +(addressBook.getDistrictName()==null?"":addressBook.getDistrictName())
                        +(addressBook.getDetail()==null?"":addressBook.getDetail())
                );

        //14.收货人
        orders.setConsignee(addressBook.getConsignee());

        ordersDao.insert(orders);

        //6.情况 当前用户购物车数据
        shoppingCartDao.delete(wrapper);
    }

    //分页查询订单
    @Override
    public Page<OrdersDto> look(int page, int pageSize) {
        //封装分页参数page和pageSize到Page对象中
        Page<Orders> ordersPage = new Page<>(page, pageSize);

        //设置分页查询条件
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(Orders::getUserId,userId);
        wrapper.orderByDesc(Orders::getOrderTime);

        //调用selectPage方法 传入ordersPage对象和wrapper对象完成分页查询
        ordersDao.selectPage(ordersPage,wrapper);

        //完善代码：响应Page<OrdersDto>
        Page<OrdersDto> ordersDtoPage = new Page<>();

        List<Orders> ordersList = ordersPage.getRecords();
        ArrayList<OrdersDto> ordersDtoList = new ArrayList<>();
        for (Orders orders : ordersList) {
            OrdersDto ordersDto = new OrdersDto();

            BeanUtils.copyProperties(orders,ordersDto);

            LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(OrderDetail::getOrderId,orders.getId());
            List<OrderDetail> orderDetailList = orderDetailDao.selectList(wrapper1);

            ordersDto.setOrderDetails(orderDetailList);
            //将ordersDto对象放入到ordersDtoList集合中
            ordersDtoList.add(ordersDto);
        }
        //将当前页要显示的数据 设置到dishDtoPage对象的records属性上
        ordersDtoPage.setRecords(ordersDtoList);
        //将总条数设置到dishDtoPage对象的total属性上
        ordersDtoPage.setTotal(ordersPage.getTotal());
        //返回Page对象【Page对象中包含当前页数据集合List和总条数】
        return ordersDtoPage;
    }

    //
    @Override
    public Page<Orders> pages(int page, int pageSize, String number, String beginTime, String endTime) {
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.like(number!=null,Orders::getNumber,number);
        qw.between(beginTime!=null&&endTime!=null,Orders::getOrderTime,beginTime,endTime);
        ordersDao.selectPage(ordersPage,qw);
        return ordersPage;
    }
}
